import axios from 'axios'
import { Toast } from 'vant'
import router from '../router'

// 开发环境
// if (process.env.NODE_ENV == 'development') {
//   axios.defaults.baseURL = 'http://10.3.144.22'
// } else {
// }


axios.defaults.baseURL = process.env.NODE_ENV == 'development' ? 'http://backend-api-01.newbee.ltd/api/v1' : 'http://backend-api-01.newbee.ltd/api/v1'


// 请求拦截
axios.interceptors.request.use(config => {
  const token = localStorage.getItem('token');
  config.headers["X-Requested-With"] = "XMLHttpRequest"
  config.headers.post["Content-Type"] = "application/json"
  if (token) config.headers["token"] = token
  return config
}, error => {
  return Promise.reject(error);
})

// 响应拦截
axios.interceptors.response.use(res => {
  if (typeof res.data !== 'object') {
    Toast.fail('服务端异常！')
    return Promise.reject(res)
  }
  if (res.data.resultCode !== 200) {
    if (res.data.message) Toast.fail(res.data.message)
    if (res.data.resultCode === 416) {
      //去登入页面
      localStorage.clear()
    }
    if (res.data.resultCode === 500) {
      router.push({ path: '/home' })
    }
    return Promise.reject(res.data)
  }

  return res.data
})
export default axios
